(function($) {

var plugin = $.AttachmentsPlugin = {
	//Nom de la classe à instancier /!\ CE NOM DOIT ETRE UNIQUE ET IDENTIQUE AU NOM JQUERY /!\
	name: 'AttachmentsPlugin'
};

//Constructeur
var AttachmentsPlugin = function(options){ // rajouter element
	if(arguments.length) {
		this._init( options );// rajouter element
	} else 
		console.log('Aucun paramètre reçu pour AttachmentsPlugin');
};

AttachmentsPlugin.prototype = {
	defaults: {
		options:{},	
		data: {},
		url: '',
		url_flash: '',
		url_silverlight: ''
	},
	
	_init: function(options){// rajouter element
		var t = this;
		
		// Public
		t.element = $(options.element);
		t.options = $.extend(true, {}, t.defaults, options);
		t.element = (typeof t.options.element != 'undefined') ? t.options.element : null;
		t.idEvent = (typeof t.options.idEvent != 'undefined') ? t.options.idEvent : 0;
		t.attachments = {};
		t.url = t.options.url;
		t.url_flash = t.options.url_flash;
		t.url_silverlight = t.options.url_silverlight;
		
		$(t.element).html(t.options.content);
		
		var plupload_settings = {
			// General settings
			runtimes : 'gears,html5,flash,silverlight,browserplus',
			url : t.url,
			max_file_size : '10mb',
			unique_names : false,
			file_data_name: 'uploaded_attachments',
		
			// Flash settings
			flash_swf_url : t.url_flash,
		
			// Silverlight settings
			silverlight_xap_url : t.url_silverlight,
		
			init : {
				FilesAdded: function(up, files) {
					$('#em-plugin-attachments-uploader_refresh').show();
				},					
				FileUploaded: function(up, file, info) {
					var response = JSON.parse(info.response);
					
					if(info.status == 200 && typeof response.result != 'undefined'){
						var attachment = {
							name : file.name,
							id : response.id
						};
						
						var attachments = {};
						attachments[response.id] = attachment;
						t.attachments[response.id] = attachment;
						
						t.submitAttachments(attachments, function(attachments){
							t.renderAttachments(attachments);
						});							   
					} else if(info.status == 200 && typeof response.error != 'undefined'){
						var type = (response.error.code == 400) ? 'warning' : 'error';
						$.pnotify({ title: 'Erreur', text: response.error.message, type: type, history: false });
					} else {
						$.pnotify({ title: 'Erreur serveur !', text: 'Une erreur inconnue est survenue', type: 'error', history: false });
					}
				},
				Error: function(up, args) {
					// Called when a error has occured
					console.log('[error] ', args);
				}
			}
		};
		
		$('.attachment_remove_action').on('click', function(e){ t.deleteAttachment(e, $(this)); });
			
		$('#em-plugin-attachments-uploader_refresh').hide();
		
		$('#em-plugin-attachments-uploader_refresh').on('click', function(e){
			e.preventDefault();
			
			var uploader = $( "#em-plugin-attachments-uploader" );
			uploader.pluploadBootstrap().destroy();
			var widget = uploader.parents('.widget');
			uploader.remove();
			widget.append('<div id="em-plugin-attachments-uploader" class="widget-content no-padding no-border"></div>');	
			$( "#em-plugin-attachments-uploader").pluploadBootstrap(plupload_settings);
			$('#em-plugin-attachments-uploader_refresh').hide();
		});
		
		$( "#em-plugin-attachments-uploader" ).pluploadBootstrap(plupload_settings);
		
	},
	
	submitAttachments : function(attachments, callback){
		callback(attachments);
	},
	
	renderAttachments : function(attachments){
		$.each(attachments, function(id, attachment){
			var collectionAttachments = $('#em-plugin-attachments-uploader_attachments');
			$('.alert', collectionAttachments).remove();
			
		    var attachmentContent = '<input type="hidden" value="'+attachment.id+'" name="'+$('li', collectionAttachments).size()+'" /><span><i class="icon-attachment"></i></span><code class="text-nowrap" style="width: 75%; vertical-align:middle;"><a class="attachment_remove_action" href="#"><i class="icon-remove"></i> Supprimer</a> - '+attachment.name+'</code></li></div>';
		    var $newAttachment = $('<li class="span12"></li>').appendTo(collectionAttachments);
		    $newAttachment.append(attachmentContent);
		    console.log($newAttachment.data('attachment'));
			
		    $('.attachment_remove_action').on('click', function(e){ t.deleteAttachment(e, $(this)); });
		});
	},
	
	deleteAttachment : function(e, elem){
		e.preventDefault();
		
		elem.parents('li').remove();

		if($('#services_emailingrequest_attachments > li').size() == 0){
			$('#services_emailingrequest_attachments').append('<li class="alert alert-warning">Aucune pièce jointe</li>');
		}
	}
};

$.fn.pluginParticipantsEvent = function(options) {

	var isMethodCall = typeof options === "string",
		args = Array.prototype.slice.call( arguments, 1 ),
		returnValue = this;

	// prevent calls to internal methods
	if ( isMethodCall && options.charAt( 0 ) === "_" ) {
		return returnValue;
	}

	if ( isMethodCall ) {
		this.each(function() {
			var instance = $.data( this, 'AttachmentsPlugin' ),
				methodValue = instance && $.isFunction( instance[options] ) ?
					instance[ options ].apply( instance, args ) :
					instance;

			if ( methodValue !== instance && methodValue !== undefined ) {
				returnValue = methodValue;
				return false;
			}
		});
	} else {
		this.each(function() {
			var instance = $.data( this, 'AttachmentsPlugin' );
			if ( !instance ) {
				$.data( this, 'AttachmentsPlugin', new AttachmentsPlugin( this, options ) );
			}
		});
	}

	return returnValue;
};

function AttachmentsEvent(_plugin){
	var t = this;
	var plugin = _plugin;

	$(plugin.element).html(plugin.settings.content);
	
	$( "#em-plugin-attachments-uploader" ).pluploadBootstrap({
		  
		// General settings
		runtimes : 'gears,html5,flash,silverlight,browserplus',
		url : 'php/plupload.php',
		max_file_size : '256kb',
		chunk_size : '64kb',
		unique_names : true,

		// Resize images on clientside if we can
		resize : { width : 320, height : 240, quality : 90 },

		// Specify what files to browse for
		filters : [
			{title : "Images", extensions : "jpg, jpeg, gif, png"},
	        {title : "Archives", extensions : "zip"}
		],

		// Flash settings
		flash_swf_url : 'plugins/plupload/plupload.flash.swf',

		// Silverlight settings
		silverlight_xap_url : 'plugins/plupload/plupload.silverlight.xap'
	});
}

// Association en tant que plugin jQuery
//$.fn.AttachmentsPlugin = plugin.AttachmentsPlugin;

// Si l'eventManager a été déclaré on le surcharge pour la gestion du plugin
if(typeof $.eventManager != 'undefined'){
	var em = $.eventManager;
	
	// Ajout du plugin au register du manager, il sera instancié par le manager automatiquement
	em.addPluginToRegister('AttachmentsPlugin', AttachmentsPlugin);
}

})(jQuery);